package cn.bellychang.interceptor;

import cn.bellychang.response.ErrorCode;
import cn.bellychang.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.CallableProcessingInterceptor;

import java.util.concurrent.Callable;

/**
 * @author ChangLiang
 * @date 2020/9/23
 */
public class TimeoutCallableProcessingInterceptor implements CallableProcessingInterceptor {

    private final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Override
    public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) throws Exception {
        LOGGER.error("callable processing timeout");
        Response response = new Response();
        response.setErrorCode(ErrorCode.REQUEST_TIMEOUT.code);
        response.setValue(ErrorCode.REQUEST_TIMEOUT.value);
        return response;
    }

    @Override
    public <T> Object handleError(NativeWebRequest request, Callable<T> task, Throwable t) throws Exception {
        LOGGER.error("callable processing error: message: {}", t.getMessage());
        Response response = new Response();
        response.setErrorCode(ErrorCode.ERROR.code);
        response.setValue(ErrorCode.ERROR.value);
        return response;
    }

    @Override
    public <T> void afterCompletion(NativeWebRequest request, Callable<T> task) throws Exception {
        LOGGER.info("callable processing completed");
    }
}
